import 'dotenv/config';

export const config = {
  // 服务器配置
  env: process.env.NODE_ENV || 'development',
  port: parseInt(process.env.PORT) || 5000,
  host: process.env.HOST || '0.0.0.0',
  
  // 数据库配置
  databaseUrl: process.env.DATABASE_URL || 'file:../data/2fa.db',
  
  // JWT配置
  jwt: {
    secret: process.env.JWT_SECRET || 'change-this-secret-in-production',
    expiresIn: process.env.JWT_EXPIRES_IN || '15m',
    refreshExpiresIn: process.env.REFRESH_TOKEN_EXPIRES_IN || '7d',
  },
  
  // 安全配置
  security: {
    bcryptRounds: parseInt(process.env.BCRYPT_ROUNDS) || 10,
    maxLoginAttempts: parseInt(process.env.MAX_LOGIN_ATTEMPTS) || 5,
    lockoutDuration: parseInt(process.env.LOCKOUT_DURATION) || 30, // 分钟
  },
  
  // CORS配置
  cors: {
    origin: process.env.CORS_ORIGIN || 'http://localhost:3000',
    credentials: true,
  },
  
  // 速率限制
  rateLimit: {
    max: parseInt(process.env.RATE_LIMIT_MAX) || 100,
    timeWindow: parseInt(process.env.RATE_LIMIT_TIMEWINDOW) || 60000, // 1分钟
  },
  
  // 会话配置
  session: {
    maxDevices: parseInt(process.env.MAX_DEVICES) || 5,
    inactivityTimeout: process.env.SESSION_INACTIVITY_TIMEOUT || '30m',
  },
  
  // 初始管理员配置
  initialAdmin: {
    username: process.env.INITIAL_ADMIN_USERNAME || 'admin',
    email: process.env.INITIAL_ADMIN_EMAIL || 'admin@example.com',
    password: process.env.INITIAL_ADMIN_PASSWORD || 'ChangeMe123!',
  },
  
  // 日志配置
  logLevel: process.env.LOG_LEVEL || 'info',
};

// 验证必需的环境变量
export function validateConfig() {
  const errors = [];
  
  if (config.env === 'production') {
    if (config.jwt.secret === 'change-this-secret-in-production') {
      errors.push('JWT_SECRET must be set in production');
    }
    if (config.jwt.secret.length < 32) {
      errors.push('JWT_SECRET must be at least 32 characters');
    }
  }
  
  if (errors.length > 0) {
    throw new Error('Configuration errors:\n' + errors.join('\n'));
  }
  
  return true;
}


